<?php
/*	Discuz第三方框架 阿里云API网关扩展
 *
 *
 */
if(!defined('IN_DISCUZ')) {
	//exit('Access Denied');
}

class Wclass_aliyun_gateWayAPI {
	
	public $Header = array();
	public $KEY ='';
	public $Secret ='';
	function __construct() {
		$this->Header = array(
			'Accept' => 'application/json',
			'Content-MD5' => '',
			'Content-Type' => 'application/text',
			'Date' => '',
			'X-Ca-Signature' => '', //签名Header
			'X-Ca-Signature-Headers' => '',//所有参与签名的Header
			'X-Ca-Timestamp' => '',//请求时间戳
			'X-Ca-Nonce' => md5(uniqid()),//请求放重放Nonce,15分钟内保持唯一,建议使用UUID
			'X-Ca-Key' => $this->KEY, //APP KEY
			'X-Ca-Version' => 1,
			'X-Ca-Stage' => 'release', //指定对象 test=测试环境
		);
	}
	public function Run($KEY,$Secret,$Method='GET',$url,$post){
		$this->KEY = $KEY;
		$this->Secret = $Secret;
		$this->Header['Date'] = gmdate('D, d M Y H:i:s \G\M\T');
		$this->Header['X-Ca-Timestamp'] = $this->getMillisecond() + 900;
		$this->Header['X-Ca-Key'] = $this->KEY;
		if($post){
			$post = http_build_query($post);
			//$this->Header['Content-Length'] = strlen($post);
		}
		
		$data = $this->Bind($Method,$url,$post);
		$return = dCurl($Method,$data['url'],$post,$data['header']);
		return $return;
	}
	
	public function Purl($url){
		$urldata = parse_url($url);
		$HTTPURL = $urldata['scheme'].'://'.$urldata['host'].$urldata['path'];
		if($urldata['query']){
			
			$urldata['query'] = str_replace(array($HTTPURL.'?',$HTTPURL),'',$url);
			$querydata = explode('&',$urldata['query']);
			$new_query = array();
			foreach($querydata as $value){
				list($k,$v) = explode('=',$value);
				if($v){
					$new_query[$k] = $v;
				}
			}
			$urldata['query'] = $new_query;
			unset($new_query);
			if($urldata['query']){
					ksort($urldata['query']);
					foreach($urldata['query'] as $key => $value){
						$urldata['querys'][$key] = $key.'='.$value;
					}
					$urldata['querys'] = '?'.implode('&',$urldata['querys']);
			}
		}
		$urldata['url'] = $HTTPURL.$urldata['querys'];
		//脱坑   阿里云网关api GET条件参与签名时，如果值被urlencode则应该使用原始字符参与签名
		foreach($urldata['query'] as $key => $value){
			$urldata['query'][$key] = $key.'='.urldecode($value);
		}
		$urldata['query'] = '?'.implode('&',$urldata['query']);
		return $urldata;
	}
	
	public function Bind($method,$url,$post){
		if($post){
			$this->Header['Content-MD5'] = base64_encode(md5($post,true));
		}
		$return = array(
			'url' => $url,
			'header' => $this->Header,
		);
		
		$urldata = $this->Purl($url);
		$return['url'] = $urldata['url'];
		$singnheader = array();
		foreach($this->Header as $key => $value){
			if(strpos($key,'X-') !== false && !in_array($key, array('X-Ca-Signature-Headers','X-Ca-Signature'))){
				$singnheader[$key] = $key.':'.$value;
			}
		}
		ksort($singnheader); //按照字典自然排序
		$return['header']['X-Ca-Signature-Headers'] = implode(',',array_keys($singnheader));
		
		
		$sign = array(
			'GET', //HTTPMethod 
			$this->Header['Accept'], //Accept 
			$this->Header['Content-MD5'], //Content-MD5 
			$this->Header['Content-Type'], //Content-Type
			$this->Header['Date'], //Date 
			implode("\n",$singnheader), //Headers 
			$urldata['path'].$urldata['query'],//Url
		);
		
		$sign = implode("\n",$sign);
		$signature = base64_encode(hash_hmac('sha256',$sign, $this->Secret, true));
		$return['header']['X-Ca-Signature'] = $signature;
		return $return;
	}
	
	
	public function getMillisecond() {
		list($t1, $t2) = explode(' ', microtime());
		return (float)sprintf('%.0f',(floatval($t1)+floatval($t2))*1000);
	}
	public function headers($d){
		$data = array();
		foreach($d as $k => $v){
			$data[] = $k.':'.$v;
		}
		return $data;
	}
}

?>